import React, { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Separator } from '@/components/ui/separator';
import { useGameStore } from '@/store/game-store';
import { 
  Users, 
  MessageCircle, 
  Trophy, 
  UserPlus, 
  Send, 
  Crown,
  Sword,
  Shield,
  Zap,
  Star,
  Gift,
  Search,
  MoreVertical,
  UserMinus,
  MessageSquare
} from 'lucide-react';

interface Friend {
  id: string;
  name: string;
  level: number;
  realm: string;
  avatar: string;
  status: 'online' | 'offline';
  lastSeen: Date;
}

interface ChatMessage {
  id: string;
  senderId: string;
  senderName: string;
  content: string;
  timestamp: Date;
  type: 'text' | 'system';
}

interface RankingPlayer {
  id: string;
  name: string;
  level: number;
  realm: string;
  avatar: string;
  power: number;
  rank: number;
}

export function SocialPage() {
  const { player } = useGameStore();
  
  // 好友系统状态
  const [friends, setFriends] = useState<Friend[]>([
    {
      id: '1',
      name: '剑仙李白',
      level: 45,
      realm: '金丹期',
      avatar: '⚔️',
      status: 'online',
      lastSeen: new Date()
    },
    {
      id: '2', 
      name: '丹师华佗',
      level: 38,
      realm: '筑基期',
      avatar: '🧙‍♂️',
      status: 'offline',
      lastSeen: new Date(Date.now() - 3600000)
    },
    {
      id: '3',
      name: '阵法大师',
      level: 52,
      realm: '元婴期',
      avatar: '🔮',
      status: 'online',
      lastSeen: new Date()
    }
  ]);

  // 聊天系统状态
  const [selectedFriend, setSelectedFriend] = useState<Friend | null>(null);
  const [chatMessages, setChatMessages] = useState<ChatMessage[]>([
    {
      id: '1',
      senderId: '1',
      senderName: '剑仙李白',
      content: '道友，最近修炼如何？',
      timestamp: new Date(Date.now() - 1800000),
      type: 'text'
    },
    {
      id: '2',
      senderId: player.id,
      senderName: player.name,
      content: '还不错，刚突破了一个小境界',
      timestamp: new Date(Date.now() - 1200000),
      type: 'text'
    },
    {
      id: '3',
      senderId: '1',
      senderName: '剑仙李白',
      content: '恭喜道友！有空一起切磋切磋',
      timestamp: new Date(Date.now() - 600000),
      type: 'text'
    }
  ]);
  const [newMessage, setNewMessage] = useState('');

  // 排行榜状态
  const [rankings, setRankings] = useState<RankingPlayer[]>([
    {
      id: '1',
      name: '无极剑圣',
      level: 99,
      realm: '大乘期',
      avatar: '👑',
      power: 99999,
      rank: 1
    },
    {
      id: '2',
      name: '九天玄女',
      level: 95,
      realm: '渡劫期',
      avatar: '🌟',
      power: 88888,
      rank: 2
    },
    {
      id: '3',
      name: '太上老君',
      level: 92,
      realm: '渡劫期',
      avatar: '🧙‍♂️',
      power: 77777,
      rank: 3
    },
    {
      id: player.id,
      name: player.name,
      level: player.level,
      realm: player.realm.name,
      avatar: player.avatar,
      power: player.attack + player.defense + player.speed,
      rank: 156
    }
  ]);

  // 搜索状态
  const [searchQuery, setSearchQuery] = useState('');
  const [searchResults, setSearchResults] = useState<Friend[]>([]);

  // 发送消息
  const sendMessage = () => {
    if (!newMessage.trim() || !selectedFriend) return;

    const message: ChatMessage = {
      id: Date.now().toString(),
      senderId: player.id,
      senderName: player.name,
      content: newMessage.trim(),
      timestamp: new Date(),
      type: 'text'
    };

    setChatMessages(prev => [...prev, message]);
    setNewMessage('');

    // 模拟好友回复
    setTimeout(() => {
      const replies = [
        '哈哈，有道理！',
        '确实如此，道友见解独到',
        '我也是这么想的',
        '受教了，多谢道友指点',
        '改天一起去历练吧'
      ];
      
      const reply: ChatMessage = {
        id: (Date.now() + 1).toString(),
        senderId: selectedFriend.id,
        senderName: selectedFriend.name,
        content: replies[Math.floor(Math.random() * replies.length)],
        timestamp: new Date(),
        type: 'text'
      };

      setChatMessages(prev => [...prev, reply]);
    }, 1000 + Math.random() * 2000);
  };

  // 添加好友
  const addFriend = (friendData: Partial<Friend>) => {
    const newFriend: Friend = {
      id: Date.now().toString(),
      name: friendData.name || '神秘修士',
      level: Math.floor(Math.random() * 50) + 1,
      realm: ['练气期', '筑基期', '金丹期', '元婴期'][Math.floor(Math.random() * 4)],
      avatar: ['🧙‍♂️', '⚔️', '🔮', '🌟'][Math.floor(Math.random() * 4)],
      status: Math.random() > 0.5 ? 'online' : 'offline',
      lastSeen: new Date()
    };

    setFriends(prev => [...prev, newFriend]);
    setSearchQuery('');
    setSearchResults([]);
  };

  // 删除好友
  const removeFriend = (friendId: string) => {
    setFriends(prev => prev.filter(f => f.id !== friendId));
    if (selectedFriend?.id === friendId) {
      setSelectedFriend(null);
    }
  };

  // 搜索玩家
  const searchPlayers = () => {
    if (!searchQuery.trim()) return;

    // 模拟搜索结果
    const mockResults: Friend[] = [
      {
        id: 'search-1',
        name: searchQuery,
        level: Math.floor(Math.random() * 50) + 1,
        realm: ['练气期', '筑基期', '金丹期'][Math.floor(Math.random() * 3)],
        avatar: '🧙‍♂️',
        status: 'online',
        lastSeen: new Date()
      }
    ];

    setSearchResults(mockResults);
  };

  // 格式化时间
  const formatTime = (date: Date) => {
    const now = new Date();
    const diff = now.getTime() - date.getTime();
    
    if (diff < 60000) return '刚刚';
    if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`;
    if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`;
    return `${Math.floor(diff / 86400000)}天前`;
  };

  // 获取排名颜色
  const getRankColor = (rank: number) => {
    if (rank === 1) return 'text-yellow-400';
    if (rank === 2) return 'text-gray-300';
    if (rank === 3) return 'text-amber-600';
    return 'text-slate-400';
  };

  return (
    <div className="min-h-screen bg-gradient-to-b from-slate-900 to-slate-800 p-4">
      <div className="max-w-7xl mx-auto space-y-6">
        {/* 页面标题 */}
        <Card className="bg-slate-800/50 border-slate-700">
          <CardHeader>
            <CardTitle className="text-2xl text-center text-slate-100 flex items-center justify-center gap-2">
              <Users className="h-6 w-6 text-blue-400" />
              仙友社交
              <Users className="h-6 w-6 text-blue-400" />
            </CardTitle>
          </CardHeader>
        </Card>

        <Tabs defaultValue="friends" className="w-full">
          <TabsList className="grid w-full grid-cols-3 bg-slate-700">
            <TabsTrigger value="friends" className="text-slate-300">
              <Users className="h-4 w-4 mr-2" />
              好友列表
            </TabsTrigger>
            <TabsTrigger value="chat" className="text-slate-300">
              <MessageCircle className="h-4 w-4 mr-2" />
              聊天室
            </TabsTrigger>
            <TabsTrigger value="ranking" className="text-slate-300">
              <Trophy className="h-4 w-4 mr-2" />
              排行榜
            </TabsTrigger>
          </TabsList>

          {/* 好友列表 */}
          <TabsContent value="friends" className="space-y-4">
            <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
              {/* 好友搜索 */}
              <Card className="bg-slate-800/50 border-slate-700">
                <CardHeader>
                  <CardTitle className="text-slate-100 flex items-center gap-2">
                    <Search className="h-5 w-5 text-green-400" />
                    寻找道友
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="flex gap-2">
                    <Input
                      placeholder="输入道友名称..."
                      value={searchQuery}
                      onChange={(e) => setSearchQuery(e.target.value)}
                      className="bg-slate-700 border-slate-600 text-slate-100"
                      onKeyPress={(e) => e.key === 'Enter' && searchPlayers()}
                    />
                    <Button onClick={searchPlayers} className="bg-green-600 hover:bg-green-700">
                      <Search className="h-4 w-4" />
                    </Button>
                  </div>

                  {searchResults.length > 0 && (
                    <div className="space-y-2">
                      <h4 className="text-sm font-semibold text-slate-300">搜索结果</h4>
                      {searchResults.map((result) => (
                        <div key={result.id} className="flex items-center justify-between p-2 bg-slate-700/50 rounded">
                          <div className="flex items-center gap-2">
                            <div className="text-2xl">{result.avatar}</div>
                            <div>
                              <div className="text-sm font-semibold text-slate-100">{result.name}</div>
                              <div className="text-xs text-slate-400">{result.level}级 {result.realm}</div>
                            </div>
                          </div>
                          <Button
                            size="sm"
                            onClick={() => addFriend(result)}
                            className="bg-blue-600 hover:bg-blue-700"
                          >
                            <UserPlus className="h-3 w-3" />
                          </Button>
                        </div>
                      ))}
                    </div>
                  )}
                </CardContent>
              </Card>

              {/* 好友列表 */}
              <Card className="lg:col-span-2 bg-slate-800/50 border-slate-700">
                <CardHeader>
                  <CardTitle className="text-slate-100 flex items-center justify-between">
                    <span className="flex items-center gap-2">
                      <Users className="h-5 w-5 text-blue-400" />
                      我的道友 ({friends.length})
                    </span>
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <ScrollArea className="h-96">
                    <div className="space-y-3">
                      {friends.map((friend) => (
                        <motion.div
                          key={friend.id}
                          initial={{ opacity: 0, y: 20 }}
                          animate={{ opacity: 1, y: 0 }}
                          className="flex items-center justify-between p-3 bg-slate-700/30 rounded-lg hover:bg-slate-700/50 transition-colors"
                        >
                          <div className="flex items-center gap-3">
                            <div className="relative">
                              <div className="text-3xl">{friend.avatar}</div>
                              <div className={`absolute -bottom-1 -right-1 w-3 h-3 rounded-full border-2 border-slate-800 ${
                                friend.status === 'online' ? 'bg-green-400' : 'bg-gray-400'
                              }`} />
                            </div>
                            <div>
                              <div className="font-semibold text-slate-100">{friend.name}</div>
                              <div className="text-sm text-slate-400">
                                {friend.level}级 {friend.realm}
                              </div>
                              <div className="text-xs text-slate-500">
                                {friend.status === 'online' ? '在线' : `${formatTime(friend.lastSeen)}`}
                              </div>
                            </div>
                          </div>

                          <div className="flex items-center gap-2">
                            <Button
                              size="sm"
                              variant="outline"
                              onClick={() => setSelectedFriend(friend)}
                              className="border-slate-600 text-slate-300 hover:bg-slate-700"
                            >
                              <MessageSquare className="h-3 w-3" />
                            </Button>
                            <Button
                              size="sm"
                              variant="outline"
                              onClick={() => removeFriend(friend.id)}
                              className="border-red-600 text-red-400 hover:bg-red-900/20"
                            >
                              <UserMinus className="h-3 w-3" />
                            </Button>
                          </div>
                        </motion.div>
                      ))}
                    </div>
                  </ScrollArea>
                </CardContent>
              </Card>
            </div>
          </TabsContent>

          {/* 聊天室 */}
          <TabsContent value="chat" className="space-y-4">
            <div className="grid grid-cols-1 lg:grid-cols-4 gap-6 h-96">
              {/* 好友列表侧边栏 */}
              <Card className="bg-slate-800/50 border-slate-700">
                <CardHeader>
                  <CardTitle className="text-slate-100 text-sm">在线道友</CardTitle>
                </CardHeader>
                <CardContent>
                  <ScrollArea className="h-64">
                    <div className="space-y-2">
                      {friends.filter(f => f.status === 'online').map((friend) => (
                        <div
                          key={friend.id}
                          onClick={() => setSelectedFriend(friend)}
                          className={`flex items-center gap-2 p-2 rounded cursor-pointer transition-colors ${
                            selectedFriend?.id === friend.id 
                              ? 'bg-blue-600/20 border border-blue-600/50' 
                              : 'hover:bg-slate-700/50'
                          }`}
                        >
                          <div className="text-lg">{friend.avatar}</div>
                          <div>
                            <div className="text-sm font-semibold text-slate-100">{friend.name}</div>
                            <div className="text-xs text-slate-400">{friend.level}级</div>
                          </div>
                        </div>
                      ))}
                    </div>
                  </ScrollArea>
                </CardContent>
              </Card>

              {/* 聊天区域 */}
              <Card className="lg:col-span-3 bg-slate-800/50 border-slate-700">
                <CardHeader>
                  <CardTitle className="text-slate-100 flex items-center gap-2">
                    <MessageCircle className="h-5 w-5 text-green-400" />
                    {selectedFriend ? `与 ${selectedFriend.name} 的对话` : '选择一位道友开始聊天'}
                  </CardTitle>
                </CardHeader>
                <CardContent className="flex flex-col h-80">
                  {selectedFriend ? (
                    <>
                      {/* 消息列表 */}
                      <ScrollArea className="flex-1 mb-4">
                        <div className="space-y-3">
                          {chatMessages
                            .filter(msg => 
                              msg.senderId === selectedFriend.id || 
                              msg.senderId === player.id
                            )
                            .map((message) => (
                            <div
                              key={message.id}
                              className={`flex ${
                                message.senderId === player.id ? 'justify-end' : 'justify-start'
                              }`}
                            >
                              <div
                                className={`max-w-xs px-3 py-2 rounded-lg ${
                                  message.senderId === player.id
                                    ? 'bg-blue-600 text-white'
                                    : 'bg-slate-700 text-slate-100'
                                }`}
                              >
                                <div className="text-sm">{message.content}</div>
                                <div className="text-xs opacity-70 mt-1">
                                  {formatTime(message.timestamp)}
                                </div>
                              </div>
                            </div>
                          ))}
                        </div>
                      </ScrollArea>

                      {/* 消息输入 */}
                      <div className="flex gap-2">
                        <Input
                          placeholder="输入消息..."
                          value={newMessage}
                          onChange={(e) => setNewMessage(e.target.value)}
                          onKeyPress={(e) => e.key === 'Enter' && sendMessage()}
                          className="bg-slate-700 border-slate-600 text-slate-100"
                        />
                        <Button onClick={sendMessage} className="bg-green-600 hover:bg-green-700">
                          <Send className="h-4 w-4" />
                        </Button>
                      </div>
                    </>
                  ) : (
                    <div className="flex-1 flex items-center justify-center text-slate-400">
                      <div className="text-center">
                        <MessageCircle className="h-12 w-12 mx-auto mb-3 opacity-50" />
                        <p>选择一位在线道友开始聊天</p>
                      </div>
                    </div>
                  )}
                </CardContent>
              </Card>
            </div>
          </TabsContent>

          {/* 排行榜 */}
          <TabsContent value="ranking" className="space-y-4">
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
              {/* 实力排行榜 */}
              <Card className="bg-slate-800/50 border-slate-700">
                <CardHeader>
                  <CardTitle className="text-slate-100 flex items-center gap-2">
                    <Trophy className="h-5 w-5 text-yellow-400" />
                    实力排行榜
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <ScrollArea className="h-96">
                    <div className="space-y-3">
                      {rankings.map((player, index) => (
                        <motion.div
                          key={player.id}
                          initial={{ opacity: 0, x: -20 }}
                          animate={{ opacity: 1, x: 0 }}
                          transition={{ delay: index * 0.1 }}
                          className={`flex items-center gap-3 p-3 rounded-lg ${
                            player.id === player.id ? 'bg-blue-600/20 border border-blue-600/50' : 'bg-slate-700/30'
                          }`}
                        >
                          <div className={`text-2xl font-bold ${getRankColor(player.rank)}`}>
                            {player.rank <= 3 ? (
                              player.rank === 1 ? <Crown className="h-6 w-6" /> :
                              player.rank === 2 ? <Star className="h-6 w-6" /> :
                              <Trophy className="h-6 w-6" />
                            ) : (
                              `#${player.rank}`
                            )}
                          </div>
                          
                          <div className="text-2xl">{player.avatar}</div>
                          
                          <div className="flex-1">
                            <div className="font-semibold text-slate-100">{player.name}</div>
                            <div className="text-sm text-slate-400">
                              {player.level}级 {player.realm}
                            </div>
                            <div className="text-xs text-slate-500 flex items-center gap-1">
                              <Zap className="h-3 w-3" />
                              战力: {player.power.toLocaleString()}
                            </div>
                          </div>

                          {player.rank <= 3 && (
                            <Badge 
                              variant="outline" 
                              className={`${
                                player.rank === 1 ? 'border-yellow-400 text-yellow-400' :
                                player.rank === 2 ? 'border-gray-300 text-gray-300' :
                                'border-amber-600 text-amber-600'
                              }`}
                            >
                              {player.rank === 1 ? '仙帝' : player.rank === 2 ? '仙君' : '仙王'}
                            </Badge>
                          )}
                        </motion.div>
                      ))}
                    </div>
                  </ScrollArea>
                </CardContent>
              </Card>

              {/* 个人统计 */}
              <Card className="bg-slate-800/50 border-slate-700">
                <CardHeader>
                  <CardTitle className="text-slate-100 flex items-center gap-2">
                    <Shield className="h-5 w-5 text-green-400" />
                    我的统计
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="text-center space-y-2">
                    <div className="text-4xl">{player.avatar}</div>
                    <h3 className="text-xl font-semibold text-slate-100">{player.name}</h3>
                    <Badge variant="outline" className="text-amber-400 border-amber-400">
                      排名 #{rankings.find(r => r.id === player.id)?.rank || 'N/A'}
                    </Badge>
                  </div>

                  <Separator className="bg-slate-600" />

                  <div className="space-y-3">
                    <div className="flex justify-between">
                      <span className="text-slate-400">等级</span>
                      <span className="text-slate-100">{player.level}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-slate-400">境界</span>
                      <span className="text-slate-100">{player.realm.name}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-slate-400">攻击力</span>
                      <span className="text-red-400">{player.attack}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-slate-400">防御力</span>
                      <span className="text-blue-400">{player.defense}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-slate-400">速度</span>
                      <span className="text-green-400">{player.speed}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-slate-400">总战力</span>
                      <span className="text-yellow-400 font-semibold">
                        {(player.attack + player.defense + player.speed).toLocaleString()}
                      </span>
                    </div>
                  </div>

                  <Separator className="bg-slate-600" />

                  <div className="space-y-2">
                    <h4 className="text-sm font-semibold text-slate-300">社交统计</h4>
                    <div className="flex justify-between">
                      <span className="text-slate-400">道友数量</span>
                      <span className="text-slate-100">{friends.length}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-slate-400">在线道友</span>
                      <span className="text-green-400">{friends.filter(f => f.status === 'online').length}</span>
                    </div>
                  </div>
                </CardContent>
              </Card>
            </div>
          </TabsContent>
        </Tabs>
      </div>
    </div>
  );
}